import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {InspectionService} from "../inspection.service";
import {StorageService} from "../../services/storage.service";
import {ConfirmationService} from "primeng/primeng";
import {FormBuilder, Validators} from "@angular/forms";
import {onlytimeValidator, timeValidator} from "../../validator/validators";

@Component({
  selector: 'app-add-cycle-time',
  templateUrl: './add-cycle-time.component.html',
  styleUrls: ['./add-cycle-time.component.scss']
})
export class AddCycleTimeComponent implements OnInit {
  @Output() closeAddCycleTimeMask = new EventEmitter();
  @Output() updateDev =new EventEmitter();
  @Output() addDev = new EventEmitter();
  @Input() state;
  @Input() currentCycleTime;
  inspectionTimeForm;
  title = '添加周期时间';
  display;
  cols;
  width;
  windowSize;
  constructor(
    private inspectionService: InspectionService,
    private storageService: StorageService,
    private confirmationService:ConfirmationService,
    fb:FormBuilder
  ) {
    this.inspectionTimeForm = fb.group({
      timeGroup:fb.group({
        startTime: ['', Validators.required],
        endTime: ['', Validators.required],
      },{validator:onlytimeValidator}),
    });
  }
  submitAddInspection = {
    "start_time":"",
    "end_time":"",
    "inspection_cycle_cid":""
  };
  ngOnInit() {
    this.windowSize = window.innerWidth;
    if(this.windowSize<1024){
      this.width = this.windowSize*0.9;
    }else{
      this.width = this.windowSize*0.8;
    }
    this.display = true;
    this.currentCycleTime = this.inspectionService.deepClone(this.currentCycleTime);
    if(this.state !== 'add'){
      this.title = '修改周期时间'
    }
    this.submitAddInspection.inspection_cycle_cid = this.storageService.getCurrentShiftCid('currentcid');
    this.cols = [
      {field: 'name', header: '开始时间'},
      {field: 'cycle', header: '结束时间'}
    ];

  }

  closeInspectionTimeMask(bool){
    this.closeAddCycleTimeMask.emit(bool)
  }
  addDevice(bool){
    this.inspectionService.addInspectionShift(this.submitAddInspection).subscribe(()=>{
      this.addDev.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试';
      }else{
        message = err ;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }
  updateDevice(bool){
    this.inspectionService.updateInspectionShift(this.currentCycleTime).subscribe(()=>{
      this.updateDev.emit(bool);
    },(err:Error)=>{
      this.confirmationService.confirm({
        message: '修改失败，请重新操作。',
        rejectVisible:false,
      })
    })
  }
  formSubmit(bool){
      if(this.state!=='update'){
        this.addDevice(bool)
      }else{
        this.updateDevice(bool)
      }
  }
}
